let musicList = []; // 音乐库

let currentIndex = 0; // 当前播放的音乐

// 加载音乐信息
$.ajax({
  type: "GET",
  url: "./music.json",
  dataType: "json",
  success: function (data) {
    musicList = data;
    render(musicList[currentIndex]);
  },
});

// 点击事件
$("#playBtn").on("click", function () {
  // console.log(111);
  if ($("audio").get(0).paused) {
    // 暂停状态
    $(this).removeClass("fa-play").addClass("fa-pause");
    $(".player-info").animate(
      {
        top: "-100%",
        opacity: 1,
      },
      "slow"
    );
    $("audio").get(0).play();
    $(".cover").css({
      "animation-play-state": "running",
    });
  } else {
    // 开始状态
    $(this).removeClass("fa-pause").addClass("fa-play");
    $(".player-info").animate(
      {
        top: "0%",
        opacity: 0,
      },
      "slow"
    );
    $("audio").get(0).pause();
    $(".cover").css({
      "animation-play-state": "paused",
    });
  }
});

$("#prevBtn").on("click", function () {
  if (currentIndex > 0) {
    currentIndex--;
  } else {
    currentIndex = musicList.length - 1;
  }
  render(musicList[currentIndex]);
  $("#playBtn").trigger("click");
});

$("#nextBtn").on("click", function () {
  if (currentIndex < musicList.length - 1) {
    currentIndex++;
  } else {
    currentIndex = 0;
  }
  render(musicList[currentIndex]);
  $("#playBtn").trigger("click");
});

$("#openModal").on("click", function () {
  $(".modal").css({
    display: "block",
  });
});

$(".modal-close").on("click", function () {
  $(".modal").css({
    display: "none",
  });
});

// 监听音乐播放
$("audio").on("timeupdate", function () {
  // console.log(111);
  const currentTime = $("audio").get(0).currentTime || 0;
  const duration = $("audio").get(0).duration || 0;
  console.log(formatTime(currentTime), formatTime(duration));
  // 设置当前播放时间
  $(".current-time").text(formatTime(currentTime));
  // 进度条
  const value = (currentTime / duration) * 100;
  $(".music_progress_line").css({
    width: value + "%",
  });
});

// 根据信息渲染页面
function render(data) {
  // console.log(data);
  $(".name").text(data.name);
  $(".singer-album").text(`${data.singer} - ${data.album}`);
  $(".time").text(data.time);
  $(".cover img").attr("src", data.cover);
  $("audio").attr("src", data.audio_url);
}

function formatTime(time) {
  let min = parseInt(time / 60);
  let sec = parseInt(time % 60);
  min = min < 10 ? "0" + min : min;
  sec = sec < 10 ? "0" + sec : sec;

  return `${min}:${sec}`;
}
